package service;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import socket.Users;

public class ServerAction {
	private MessageHandler messageHandler;
	
	public ServerAction(ObjectOutputStream out, ObjectInputStream in) {
		messageHandler = new MessageHandler(out, in);
	}
	
	public void exit() throws IOException {
		messageHandler.sendMessage("goodbye");
		System.out.println("Connection closed");
	}
	
	public void unknown() throws IOException {
		messageHandler.sendMessage("Unknown command");
	}
	// [V] Add 3 methods
	public String writemsg() throws IOException, ClassNotFoundException {
		messageHandler.sendMessage("Enter message");
		return messageHandler.readMessage();
	}
	
	public void send(String msg) throws IOException {
		messageHandler.sendMessage(msg);
	}
	
	public boolean authentication() throws IOException, ClassNotFoundException{
		
		boolean isAuthenticated = false;
		
		String login = null;
		String password = null;
	
		while (!isAuthenticated){
			messageHandler.sendMessage("Enter login and password:");
			login = messageHandler.readMessage();
			password = messageHandler.readMessage();
			isAuthenticated = Users.dataCheck(login, password);
			if (isAuthenticated){
				System.out.println("Authenticated user with login: " + login + ", password: " + password);
				messageHandler.sendMessage("Welcome to chat");
				break;
			}
			
			messageHandler.sendMessage("Do you want to try again? Enter y/n: ");
			if (messageHandler.readMessage().equals("n")){
				exit();
				break;
			}
		}
		return isAuthenticated;
	}
}
